package edu.sdwu.liqing.qasystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import edu.sdwu.liqing.qasystem.controller.QaQuestionController;
import edu.sdwu.liqing.qasystem.entity.EsAnswerEntity;
import edu.sdwu.liqing.qasystem.entity.QaAnswer;
import edu.sdwu.liqing.qasystem.entity.QaQuestion;
import edu.sdwu.liqing.qasystem.entity.QaUser;
import edu.sdwu.liqing.qasystem.mapper.EsAnswerMapper;
import edu.sdwu.liqing.qasystem.mapper.QaAnswerMapper;
import edu.sdwu.liqing.qasystem.service.IQaAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.sdwu.liqing.qasystem.service.IQaQuestionService;
import edu.sdwu.liqing.qasystem.util.OperateUtil;
import edu.sdwu.liqing.qasystem.util.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 问题回答表  服务实现类
 * </p>
 *
 * @author liqing@sdwu.edu
 * @since 2020-04-05
 */
@Service
public class QaAnswerServiceImpl extends ServiceImpl<QaAnswerMapper, QaAnswer> implements IQaAnswerService {

    @Autowired
    IQaQuestionService questionService;

    @Autowired
    OperateUtil operateUtil;

    @Autowired
    RequestUtil requestUtil;

    @Autowired
    EsAnswerMapper esAnswerMapper;

    //这里设置成synchronized 强制线程安全 因为同时回答两个问题可能会造成回答数更新不正确
    @Transactional
    @Override
    public synchronized boolean save(QaAnswer qaAnswer) {
        if (StringUtils.isAnyBlank(qaAnswer.getContent(), qaAnswer.getQuestionId())) {
            return false;
        }
        //新增问题
        //获取该问题的信息
        QaQuestion question = questionService.getById(qaAnswer.getQuestionId());
        if (Objects.isNull(question)) {
            //如果问题不存在
            return false;
        }
        //这里和提问的权限一样
        if (!operateUtil.canAddQuestion(question.getModuleId())) {
            //如果无法回答
            return false;
        }
        //保存问题
        boolean flag = super.save(qaAnswer);
        if (flag) {
            //保存成功， 回答数加一
            question.setAnswerNum(question.getAnswerNum() + 1);
            //更新回答数
            questionService.updateById(question);

            EsAnswerEntity entity = new EsAnswerEntity();
            entity.setContent(QaQuestionServiceImpl.filterChinese(qaAnswer.getContent()));
            entity.setQuestionId(qaAnswer.getQuestionId());
            entity.setId(qaAnswer.getId());
            esAnswerMapper.save(entity);
        }
        return flag;
    }

    @Override
    public boolean update(QaAnswer qaAnswer) {
        if (StringUtils.isBlank(qaAnswer.getId())) {
            return false;
        }
        QaAnswer answer = super.getById(qaAnswer.getId());
        if (Objects.isNull(answer) || !operateUtil.canOperate(answer)) {
            return false;
        }
        return super.updateById(qaAnswer);
    }

    //也是强制线程同步，否则容易出现数量不对的情况
    //开启事务
    @Transactional
    @Override
    public synchronized boolean delete(String id) {
        if (StringUtils.isBlank(id)) {
            return false;
        }
        QaAnswer answer = super.getById(id);
        if (Objects.isNull(answer) || !operateUtil.canOperate(answer)) {
            return false;
        }
        boolean flag = super.removeById(id);
        if (flag) {
            QaQuestion question = questionService.getById(answer.getQuestionId());
            if (Objects.nonNull(question)) {
                if (question.getAnswerNum() > 0) {
                    question.setAnswerNum(question.getAnswerNum() - 1);
                }
                questionService.updateById(question);
            }
        }
        return flag;
    }

    @Override
    public QaAnswer get(String id) {
        QaAnswer answer = super.getById(id);
        return Objects.nonNull(answer) ? answer: new QaAnswer();
    }

    @Override
    public List<QaAnswer> listByQuestionId(String questionId) {
        QaUser user = requestUtil.getCurrentUser();
        QueryWrapper<QaAnswer> qw = Wrappers.query();
        qw.eq("question_id", questionId);
        qw.orderByDesc("create_time");
        List<QaAnswer> answerList = super.list(qw);
        if (CollectionUtils.isEmpty(answerList)) {
            return Lists.newArrayListWithExpectedSize(0);
        }
        answerList.parallelStream().forEach(i-> {
            i.setCanOperate(StringUtils.containsIgnoreCase("ADMIN", user.getRoleName()) || StringUtils.equals(user.getId(), i.getCreatedBy()));
        });
        return answerList;
    }
}
